import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-09-08
 * Time: 14:01
 */
class Solution5 {
    public String decodeString(String s) {
        Stack<Integer> num = new Stack<>();
        Stack<StringBuilder> stack = new Stack<>();
        // 先放一个空字符串 细节 避免
        stack.push(new StringBuilder());
        int n = s.length();
        char[] s1 = s.toCharArray();
        int i = 0;
        while (i < n) {
            if (s1[i] >= '0' && s1[i] <= '9') {
                // 提取数字
                int tmp = 0;
                while (i < n && s1[i] >= '0' && s1[i] <= '9') {
                    tmp = tmp * 10 + (s1[i] - '0');
                    i++;
                }
                num.push(tmp);
            } else if (s1[i] == '[') {
                i++;
                StringBuilder tmp = new StringBuilder();
                while (i < n && s1[i] >= 'a' && s1[i] <= 'z') {
                    tmp.append(s1[i]);
                    i++;
                }
                stack.push(tmp);
            } else if (s1[i] == ']') {
                // 解析
                StringBuilder tmp = stack.pop();
                int k = num.pop();

                while (k != 0) {
                    stack.peek().append(tmp);
                    k--;
                }
                i++;
            } else {
                StringBuilder tmp = new StringBuilder();
                while (i < n && s1[i] >= 'a' && s1[i] <= 'z') {
                    tmp.append(s1[i]);
                    i++;
                }
                stack.peek().append(tmp);
            }
        }
        return stack.pop().toString();
    }
}